import axios from 'axios';
import fs from 'fs'
import GLOBAL from "./GLOBAL.js";

async function getAllFunctions(pre) {
    let url = pre + 'system/functions';
    await axios.get(url)
        .then(function (response) {
            // 函数列表
            let data = response.data;
            console.log(data.length, "functions in total")
            console.log(response.data);
        })
        .catch(function (error) {
            console.log(error);
        });
}

async function invokeSingleFunction(pre, funcName, params) {
    /*
    pre: OpenFaaS链接前缀
    funcName: 函数名
    params: 函数参数
     */
    if (typeof params != 'string') {
        params = JSON.stringify(params);
    }
    console.log("Invoking:", funcName)
    console.log("Input:", params)
    let callFuncUrl = pre + 'function/' + funcName;
    let st = new Date().getTime();
    let newData;
    // 发送函数请求
    await axios.post(callFuncUrl, params)
        .then(function (response) {
            let et = new Date().getTime();
            // type is definitely string
            console.log("Output Type:", typeof response.data);
            console.log("Output data:", response.data, "ms");
            console.log("End Time:", et - st, "ms");
            newData = `${et - st},${response.data}`
        })
        .catch(function (error) {
            console.log(error);
        });
    if (false) {
        // 请求获取资源情况
        let backEndUrl = "http://"
        let arch = funcName.substring(0, funcName.indexOf("-"))
        console.log("Arch:", arch)
        switch (arch) {
            case "x86":
                backEndUrl = backEndUrl.concat(GLOBAL.AUTH_x86swarm.HOST + ":7280")
                break;
            case "riscv64":
                backEndUrl = backEndUrl.concat(GLOBAL.AUTH_riscv64.HOST + ":7280")
                break;
            case "swarm":
                backEndUrl = backEndUrl.concat(GLOBAL.AUTH_x86swarm.HOST + ":7280")
                break;
            default:
                console.log("Unknown Arch Name:", arch)
                return
        }
        backEndUrl = backEndUrl + "/get/"
        console.log(backEndUrl)
        await axios.get(backEndUrl)
            .then(response => {
                let psutilDataStr = response.data
                newData = newData.concat(psutilDataStr)
            })
            .catch(error => {
                console.log(error);
            });
    }
    // 追加数据
    console.log(newData)
    await fs.appendFileSync("./data/" + funcName, newData + "\n")
    console.log("------- ------- -------")
}

async function loopInvokeSingleFunction(pre, funcName, count) {
    /*
    pre: OpenFaaS链接前缀
    funcName: 函数名
    count: 循环调用次数
     */
    // 创建数据文件
    // fs.writeFileSync("./data/" + funcName + "-" + new Date().getTime(), `EndTime,ExecTime\n`)
    fs.writeFileSync("./data/" + funcName, `EndTime,ExecTime,CPU,Memory,Disk\n`)
    // 动态加载模块, 区分x86和riscv64
    let moduleName = funcName.substring(funcName.indexOf("-") + 1)
    console.log("Module Name:", moduleName)
    let funcModule = await import("./function/" + moduleName + ".js")
    // 获取模块中的参数生成器
    let paramsGenerator = funcModule.default["paramsGenerator"]
    // 循环调用函数
    for (let i = 1; i <= count; i++) {
        console.log("loop count:", i)
        await invokeSingleFunction(pre, funcName, paramsGenerator())
    }
}

export default {
    getAllFunctions,
    invokeSingleFunction,
    loopInvokeSingleFunction,
}